<template>
  <div class="qr" :ref="uuid">
    <div class="box">
         <img class="qr__img" :src="qrBase64" />
    <h1 class="black">你好呀掘金！</h1>
    <h1 class="black">{{new Date().getFullYear()}}</h1>
    </div>
   

  </div>
</template>

<script>
import QRcode from 'qrcode'
import html2canvas from 'html2canvas'
export default {
  data () {
    return {
      qrBase64: '',
      qrContent:'https://juejin.cn',
      uuid:'qrCode'
    }
  },
  watch: {
    qrContent: {
      handler: function () {
        this.init();
      },
      immediate: true
    }
  },
  methods: {
    async init () {
      this.qrBase64 = await this.createQR(this.qrContent)
    },
    // 生成二维码
    createQR (content, options) {
      return new Promise((resolve, reject) => {
        QRcode.toDataURL(content, options).then(url => {
          resolve(url)
        })
      })
    },
    createCanvas () {
        return new Promise((resolve, reject) => {
        const container = this.$refs[this.uuid]
        html2canvas(container).then(canvans => {
            const base64 = canvans.toDataURL('image/png')
            resolve(base64)
        })
        })
    },
    // 需要等图片加载完才能生成canvas
    async imgLoad () {
      const canvansBase64 = await this.createCanvas()
      console.log(canvansBase64) // 生成二维码+文案图片
    }
  }
}
</script>

<style scoped>
.qr{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.qr__img{
  width: 200px;
  height: 200px;
}
.box {
  width: 200px;
  height: fit-content;
  border: 1px solid #eee;

  align-items: center;
}
.black {
    text-align: center;
}
</style>

